package com.zxq.uart.mqtt;
import com.zxq.uart.config.MqttConfig;
import com.zxq.uart.fegin.client.ShiLuWenGanFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class ChargeMqttClient {

    @Autowired
    MqttConfig mqttConfig;

    @Autowired
    ShiLuWenGanFeignClient feignClient;


    MqttClient mqttClient;








    /**初始化连接*/
    @PostConstruct
    public  void  initMqttClient() {
        //初始化连接设置对象
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
        //这里设置为true表示每次连接到服务器都以新的身份连接
        mqttConnectOptions.setCleanSession(true);
        //设置连接超时时间，单位是秒
        mqttConnectOptions.setConnectionTimeout(10);
        //设置持久化方式
        MemoryPersistence memoryPersistence = new MemoryPersistence();

        mqttConnectOptions.setUserName(mqttConfig.getUsername());
        mqttConnectOptions.setPassword(mqttConfig.getPassword().toCharArray());

        mqttClient = null;
        if(null != mqttConfig.getClientID()) {
            try {
                mqttClient = new MqttClient(mqttConfig.getUrl(), mqttConfig.getClientID(),memoryPersistence);
            } catch (MqttException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //设置连接和回调
        if(null != mqttClient) {
            if(!mqttClient.isConnected()) {
                //创建回调函数对象
                MQTTReceiveCallback MQTTReceiveCallback = new MQTTReceiveCallback(this,feignClient);
                //客户端添加回调函数
                mqttClient.setCallback(MQTTReceiveCallback);
                //创建连接
                try {
                    mqttClient.connect(mqttConnectOptions);
                    subTopic(mqttConfig.getSubTopic(),mqttClient);
                } catch (MqttException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }else {
            System.out.println("mqttClient为空");
        }
        System.out.println("连接状态"+mqttClient.isConnected());
    }



    /**发布消息*/
    public  void publishMessage(String pubTopic, byte[] message) {
        if(null != mqttClient&& mqttClient.isConnected()) {
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setQos(1);
            /**
             * 这里错了，getyBytes是ascii编码，你是hex编码
             */
            mqttMessage.setPayload(message);
            MqttTopic topic = mqttClient.getTopic(pubTopic);

            if(null != topic) {
                try {
                    MqttDeliveryToken publish = topic.publish(mqttMessage);
                    if(!publish.isComplete()) {
                        System.out.println("消息发布成功");
                    }
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    /**订阅主题*/
    protected   void subTopic(String topic,MqttClient mqttClient) {
        if(null != mqttClient&& mqttClient.isConnected()) {
            try {
                mqttClient.subscribe(topic, 1);
                System.out.println("mqttClient is normal");
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("mqttClient is error");
        }
    }


}
